import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Table,
  Modal,
  Slider,
  Row,
  Col,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import { Link } from 'dva/router';
import G from '../../utils/g';
import moment from 'moment';
import Uploader from '../Goods/Uploader';
import GoodsModal from '../Sales/GoodsModal';

const InputGroup = Input.Group;
const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;

@connect(({loading}) => ({
  submitting: loading.effects['form/submitRegularForm'],
}))
@Form.create()
export default class BasicForms extends PureComponent {
  state = {
    imgsFileList : [],
    detail : {},
    entry : [],
    modalVisible : false,
    selectedGoods : [],
    tempIndex : '', //临时修改商品顺序序号
  };

  componentDidMount() {
    const {dispatch, location} = this.props;
    this.id = G.getUrlValue('id', location.search);
    if (typeof this.id != 'undefined') {
      dispatch({
        type: 'activities/getDetail',
        payload: {
          id: this.id
        }
      }).then((res)=> {
        console.log(res);
        //this.setState(newState);
        try{
          this.setState({
            detail : res,
            entry : JSON.parse(res.entries[0].content)
          });
        }catch(err){
          console.log(err);
          message.error('详情数据报错');
        }
        
      });
    }
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });

  };

  changeSelectedGoods = (goods)=>{  //从弹框中获取到选中的商品
    console.log("goods",goods);
    // this.setState({
    //   selectedGoods : goods
    // });
    if(goods.length == 1){
      //this.handleModalVisible(false);
      const {entry , tempIndex} = this.state;
      let newEntry = [...entry];
      newEntry[tempIndex].url = `/detail?id=${goods[0].id}` ;  //生成H5的访问地址，小程序自动拼接
      this.setState({
        entry : newEntry,
        modalVisible : false
      });
    }

  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return false;
      }
      values.entries = [
        {
          type : 0,  //用于展示类型，竖排列表图片为0
          content : JSON.stringify(this.state.entry),
          orders : 0,
        }
      ]

      if(this.id){values.id = Number(this.id);}

      this.props.dispatch({
        type: 'activities/saveActivity',
        payload: values,
      }).then(res=>{
        if(res && !this.id){  //新增才会清除表单,修改不需要
          this.props.form.resetFields();  //重置绑定表单数据
          this.setState({
            entry : []
          });
        }
      });
    });
  };

  bindImgsChange = (file,index)=> {
    console.log(index);
    let entry = [...this.state.entry];
    entry[index].image = file.length == 0 ? '' : file[0].url;  //可能删除为0
    this.setState({
      entry
    });
    //console.log(this.postData);
  };

  bindUrlInput = (e, index)=>{
    console.log(index);
    let entry = [...this.state.entry];
    entry[index].url = e.target.value;
    this.setState({
      entry
    });
  }
  bindAddContent = ()=>{  //添加子项
    let entry = [...this.state.entry];
    entry.push({
      url : "",
      image : ""
    });

    this.setState({
      entry
    });
  }
  bindDelContent = (index)=>{
    let entry = [...this.state.entry];
    entry.splice(index,1);
    this.setState({entry});
  }

  bindSelectUrlMode = (value, index)=>{
    console.log('value',value);
    if(value == 'goods'){
      this.handleModalVisible(true);
      this.setState({
        tempIndex : index
      });
    }
  }

  render() {
    const {modalVisible, selectedGoods, detail, imgsFileList, entry} = this.state;
    const {getFieldDecorator, getFieldValue} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    const tableItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 19},
        md: {span: 19},
      },
    };

    console.log('entry', entry);

    return (
      <div>
        <Card bordered={false}>
          <Row>
            <Col md={6}>
              <div style={{height:'500px','overflowY':'auto',border:'1px solid #d9d9d9',borderRadius:'3px'}}>
                {
                  entry.map((v, i)=>{
                    return <img key={`${i} + ${v.image}`} src={v.image} width="100%" />
                  })
                }
              </div>
            </Col>
            <Col md={18}>
              <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
            <FormItem {...formItemLayout} label="活动名称" help="最多支持50个字">
              {getFieldDecorator('title', {
                initialValue: detail.title,
                rules: [
                  {
                    required: true,
                    message: '请输入活动名称',
                    max:50
                  },
                ],
              })(<Input placeholder="请输入活动名称"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="描述">
              {getFieldDecorator('desc', {
                initialValue: '',
                rules: [
                  {
                    message: '请输入描述',
                  },
                ],
              })(
                <TextArea
                  style={{minHeight: 32}}
                  placeholder="请输入描述"
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="上架状态">
              {
                getFieldDecorator('status', {
                  initialValue: detail.status || 1,
                })(
                  <Radio.Group>
                    <Radio value={1}>立即上架</Radio>
                    <Radio value={0}>暂不上架</Radio>
                  </Radio.Group>
                )
              }
            </FormItem>
            <FormItem {...tableItemLayout} label="内容" >
              {
                entry.map((v,index)=>{
                  return <Card key={v.image + index} style={{marginBottom : '8px'}}>
                    <Row>
                      <Col md={6}>
                        <Uploader
                          length={1}
                          fileList={ v.image ?
                            [{
                              uid: G.uuid(16),
                              name: G.uuid(16),
                              status: 'done',
                              url: v.image,
                            }] : []
                          }
                          onChange={(file)=>{this.bindImgsChange(file, index)}}
                        />
                      </Col>
                      <Col md={18}>

                        <InputGroup compact>
                          <Select defaultValue="sample" onSelect={(value)=>{this.bindSelectUrlMode(value,index)}}>
                            <Option value="sample">普通地址</Option>
                            <Option value="goods">商品详情</Option>
                          </Select>
                          <Input  style={{ width: '70%' }} placeholder="链接地址(非必填)" value={v.url} onChange={(e)=>{this.bindUrlInput(e, index)}} />
                        </InputGroup>

                        <Button style={{marginTop:'16px',float : 'right'}} onClick={()=>{this.bindDelContent(index)}}>删除</Button>
                      </Col>
                    </Row>
                  </Card>
                })
              }

              <Button onClick={this.bindAddContent}>添加内容</Button>
            </FormItem>

            <FormItem {...submitFormLayout} style={{marginTop: 32}}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{marginLeft: 8}}><Link to={`/index/activity`}>返回</Link></Button>
            </FormItem>
          </Form>
            </Col>
          </Row>

        </Card>
        <GoodsModal
          type = ""
          dispatch={this.props.dispatch}
          modalVisible={modalVisible}
          handleHide={this.handleModalVisible}
          selectedRows = {selectedGoods}
          changeSelectedGoods = {this.changeSelectedGoods}
        />
      </div>
    );
  }
}
